$(function() {

// --------------------------------------------------------------------------------------------------------------------
// -------------------------------付款界面-----------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
	// 弹窗样式
  function layerCss(){
    $(".layui-layer").css("border-radius","10px")
    $(".layui-layer-setwin .layui-layer-close2").css({"right":"-40px","top":"0px"});
    $(".layui-layer-ico").css("background","url("+jumpUrl+"/img/question2/iconlayer.png)");
  }

  $(".order-pay .checkboxIcon").click(function(){
    $(".checkboxIcon").removeClass("checkedIcon");
    $(this).addClass("checkedIcon");
  });
// 获取钱包金额
  if(!islogin == "" || !islogin == null){
    var wallet_url = jumpUrl+"/center/pay/question/"+order_id+"/view?type=1";
    $.get(wallet_url,function(data){
	    },'json').success(function(data) {
	    var obj = data.data;
	    console.info(obj);
	      $("#money").text(obj.money);
	      $(".moneyNum").text(obj.price);
	      $(".OrderNumber").text(obj.order_no);
	      $(".OrderType").text(obj.type);
	      $("#type").text(obj.type);
	      $(".submit-but").attr("data-id",obj.product_id);

	});
    
  }

// 开始支付
  $(".submit-but").click(function(){
  	var totalMoney = $(".moneyNum").text();
  	var question_type = $(".OrderType").text();
  	var in_question_id = $(".submit-but").attr("data-id");
    var pay_type1 = $(".checkedIcon").attr("data-href");
    var money_num = $(".moneyNum").text();
    var type_subject = $("#type").text();
    var type_body = $("#type").text();
    var product_id = order_id;
    var user_id = $(this).attr("data-id");
    var money_in_user_id = "";
    if (pay_type1 == "weixin") {        // 微信支付
        $(".content-box").html("");
        var totalMoney = money_num;
        var _token = $("input[name='_token']").val();
        // var url = jumpUrl+"/wallet/recharge";
        var loading = layer.msg('加载中...', {icon: 16});
        var params = {};
        params.device = 'pc';
        params.channel = 'wx_pub_qr';
        params.amount = money_num*100;
        params.subject = type_subject;
        params.body = type_body;
        params.product_id = product_id;
        params.current_user_id = from_user_id;
        params.metadata = {};
        params.metadata.pay_type = 'wallet_reward';
        params.metadata.user_id = user_id;
        params.metadata.from_user_id = from_user_id;
        var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
        var qr_code_url;
        $.post(wechat_qr_params_url,params,function(data){
          },'json').error(function(data) {
              var obj = $.parseJSON(data.responseText);
              layer.msg(obj.error_messages);
          }).success(function(data) {
              qr_code_url = data.credential.wx_pub_qr;
              charge_id = data.id;
              qr_payment_popup();
              check_payment(charge_id);
              var str = ''
                str +='<img src="http://paysdk.weixin.qq.com/example/qrcode.php?data='+qr_code_url+'" style="width:250px;height:250px;border-radius: 10px;" />';
                  str +='<p style="text-align:center;font-size:20px;">[ 扫描二维码支付 ]</p>';
              $(".content-box").append(str);
          });
      function check_payment(charge_id){
        var t1;
        var sum =0;
        function update_notify(){
            sum++;
            if(sum>600){window.clearInterval(t1);return false;}
            if(sum>180){
              m = sum%10;
              if(m!=0){return false;}
            }
            $(".sum").html(sum);
            var payment_query_url = jumpUrl + '/payment_gateway/query/'+charge_id;
              $.get(payment_query_url, function(data){
                }, "json").error(function(data) {
                      var status_code = $.parseJSON(data.responseText);
                      layer.msg(status_code.message);
                }).success(function(data) {
                    var obj = data;
                    if(obj.paid==true) {
                      layer.msg("微信支付成功");
                      var view_url =  JSON.parse(localStorage.getItem('view_url'));
			          window.location.href = view_url;
			          localStorage.removeItem("view_url");

                  }
                });
          }
          t1 = window.setInterval(function() {
            popup_visible = $(".content-box").is(":visible");
            if (popup_visible) {
              update_notify();
            }
            console.log('isvisible', $(".content-box").is(":visible"));
          },1000);
        window.onblur = function(){
          clearInterval(t1);
        }
        window.onfocus = function(){
          t1 = setInterval(function(){
            popup_visible = $(".content-box").is(":visible");
            if (popup_visible) {
              update_notify();
            }
          }, 1000 );
        }
      };
      // 微信扫码付费弹出框
      function qr_payment_popup(){
        var Popup02 = $(".content-box");
        layer.open({
              type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
              title: false, //标题
              closeBtn: true,  //关闭按钮
              shade:0.3,  //遮罩默认是0.3透明度
              area: ['250px', '300px'],
              skin: 'yourclass', //样式类名
              content: Popup02 //内容
            });
        	layerCss();
      };
      return false;


    }else if (pay_type1 == "alipay") {    // 支付宝支付
      layer.msg("支付宝支付未完成");
      return false;

    }else if(pay_type1 == "wallet") {   // 钱包支付
      var loading = layer.msg('加载中...', {icon: 16});
      var url = jumpUrl+"/wallet/reward";
      $.post(url,{"money":money_num,"user_id":user_id,"order_id":order_id},function(data){
        },'json').error(function(data) {
            var obj = $.parseJSON(data.responseText);
            layer.msg(obj.error_messages);
        }).success(function(data) {
	      	$("#money").text(data.data.money);
            layer.msg("钱包支付成功");
            var view_url =  JSON.parse(localStorage.getItem('view_url'));
            window.location.href = view_url;
            localStorage.removeItem("view_url");
        });
      return false;
    }else{
      layer.msg("请选择付款类型");
      return false;
    }


  });


})
